<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Kelas_santri extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->library('flexigrid');
        $this->load->library('form_validation');
		$this->load->library('session');
        $this->load->helper('flexigrid');
        $this->load->helper(array('form', 'url'));
        $this->load->model('kelas_santri_model');
        $this->load->model('kelas_model');
        $this->load->model('santri_model');
    }

    //load Grid
    function index($id_kelas) {
        if ($this->session->userdata('username') == NULL) {
            redirect('login');
        } else {
            $colModel['no'] = array('No', 30, TRUE, 'center', 0);
			$colModel['Munakosah'] = array('No Induk', 150, TRUE, 'center', 1);
            $colModel['Nama_Santri'] = array('Nama Santri', 250, TRUE, 'center', 1);
            $colModel['Nilai_Teori'] = array('Nilai Teori', 70, TRUE, 'center', 1);
            $colModel['Nilai_Praktek'] = array('Nilai Praktek', 70, TRUE, 'center', 1);

            //get_class_name
			$hasil = $this->kelas_model->selectone($id_kelas);
			foreach ($hasil->result() as $row) {
                $nama_kelas = $row->NAMA_KELAS;
            }
			$this->session->set_userdata('id_kelas', $id_kelas);
			$this->session->set_userdata('nama_kelas', $nama_kelas);

            $gridParams = array(
                'width' => 'auto',
                'height' => 300,
                'rp' => 15,
                'rpOptions' => '[5,10,15,20,25,40]',
                'pagestat' => 'Menampilkan: {from} hingga {to} dari {total} data.',
                'blockOpacity' => 0.5,
                'title' => 'Daftar Santri</br>Periode : '.$this->session->userdata('nama_periode').'</br>Kelas : '.$nama_kelas.'',
                'showTableToggleBtn' => true
            );

            $buttons[] = array('Tambah Santri', 'add', 'spt_js');
            $buttons[] = array('separator');
            $buttons[] = array('Perbarui Nilai Santri', 'update', 'spt_js');
            $buttons[] = array('separator');
			// $buttons[] = array('Cetak Absensi', 'print', 'spt_js');
            // $buttons[] = array('separator');
            $buttons[] = array('Hapus', 'delete', 'spt_js');
			$buttons[] = array('separator');
            $buttons[] = array('Kembali ke daftar kelas', 'back', 'spt_js');


            // mengambil data dari file controler ajax pada method grid_berkas
            $grid_js = build_grid_js('flex1', site_url("kelas_santri/grid_foto/".$id_kelas.""), $colModel, 'Munakosah', 'asc', $gridParams, $buttons);

            $data['added_js'] =
                    "<script type='text/javascript'>
        function spt_js(com,grid)
        {
                if (com=='Tambah Santri')
                {
                        location.href='" . base_url() . "index.php/kelas_santri/pilih_santri';
                }
                
                if (com=='Perbarui Nilai Santri')
                {
                        location.href='" . base_url() . "index.php/kelas_santri/form_nilai';
                }
				
				if (com=='Cetak Absensi')
                {
                        location.href='" . base_url() . "index.php/kelas_santri/generate_absensi';
                }
				
				if (com=='Kembali ke daftar kelas')
                {
                        location.href='" . base_url() . "index.php/kelas/index/".$this->session->userdata('id_periode')."';
                }

                if (com=='Hapus')
                        {
                           if($('.trSelected',grid).length>0){
                                   if(confirm('Anda yakin menghapus ' + $('.trSelected',grid).length + ' santri?')){
                                                var items = $('.trSelected',grid);
                                                var itemlist ='';
                                                for(i=0;i<items.length;i++){
                                                        itemlist+= items[i].id.substr(3)+',';
                                                }
                                                $.ajax({
                                                   type: 'POST',
                                                   url: '" . base_url() . "index.php/kelas_santri/delete" . "',
                                                   data: 'items='+itemlist,
                                                   success: function(data){
                                                        $('#flex1').flexReload();
                                                   }
                                                });
                                        }
                                } else {
                                        return false;
                                }
                        }

        }
        </script>
        ";


            $data['js_grid'] = $grid_js;
            $data['content'] = $this->load->view('grid', $data, true);
            $this->load->view('main', $data);
        }
    }

    function grid_foto($id_kelas) {
        $valid_fields = array('Foto_Santri', 'Nama_Santri', 'Munakosah', 'Asal_Santri', 'Email_Santri');
        $this->flexigrid->validate_post('Foto_Santri', 'asc', $valid_fields);
        $records = $this->kelas_santri_model->get_data_santri($id_kelas);
        $this->output->set_header($this->config->item('json_header'));
        $no = 0;

        foreach ($records['records']->result() as $row) {
            $record_items[] = array(
                $row->id_kelas_santri,
                $no = $no + 1,
                $row->munakosah,
				$row->nama_santri,
                $row->nilai,
                $row->nilai_praktek
            );
        }

        if (isset($record_items))
            $this->output->set_output($this->flexigrid->json_build($records['record_count'], $record_items));
        else
            $this->output->set_output('{"page":"1","total":"0","rows":[]}');
    }

	
	
	//-------------------------Pilih santri--------------------//
    function pilih_santri() {
        if ($this->session->userdata('username') == NULL) {
            redirect('login');
        } else {
            $colModel['no'] = array('No', 30, TRUE, 'center', 0);
            $colModel['Munakosah'] = array('No Induk', 150, TRUE, 'center', 1);
			$colModel['Nama_Santri'] = array('Nama Santri', 250, TRUE, 'center', 1);
            $colModel['Asal_Santri'] = array('Asal', 250, TRUE, 'center', 1);
            $colModel['Telepon_Santri'] = array('Telepon Santri', 200, TRUE, 'center', 1);

            $nama_kelas = $this->session->userdata('nama_kelas');


            $gridParams = array(
                'width' => 'auto',
                'height' => 300,
                'rp' => 10,
                'rpOptions' => '[5,10,15,20,25,40]',
                'pagestat' => 'Menampilkan: {from} hingga {to} dari {total} data.',
                'blockOpacity' => 0.5,
				'title' => 'Daftar Data Santri</br>Periode : '.$this->session->userdata('nama_periode').'</br>Kelas : '.$nama_kelas.'',
                'showTableToggleBtn' => true
            );

            $buttons[] = array('Tambahkan santri ke kelas', 'add', 'spt_js');
			$buttons[] = array('separator');
            $buttons[] = array('Kembali ke daftar santri', 'back', 'spt_js');


            // mengambil data dari file controler ajax pada method grid_berkas
            $grid_js = build_grid_js('flex1', site_url("kelas_santri/grid_pilih_santri"), $colModel, 'Nama_Santri', 'asc', $gridParams, $buttons);

            $data['added_js'] =
                    "<script type='text/javascript'>
        function spt_js(com,grid)
        {
				if (com=='Kembali ke daftar santri')
                {
                        location.href='" . base_url() . "index.php/kelas_santri/index/".$this->session->userdata('id_kelas')."';
                }
				
                if (com=='Tambahkan santri ke kelas')
                        {
                           if($('.trSelected',grid).length>0){
                                   if(confirm('Tambahkan ' + $('.trSelected',grid).length + ' data santri?')){
                                                var items = $('.trSelected',grid);
                                                var itemlist ='';
                                                for(i=0;i<items.length;i++){
                                                        itemlist+= items[i].id.substr(3)+',';
                                                }
                                                $.ajax({
                                                   type: 'POST',
                                                   url: '" . base_url() . "index.php/kelas_santri/add" . "',
                                                   data: 'items='+itemlist,
                                                   success: function(data){
														alert(data);
														window.location.href = '" . base_url() . "index.php/kelas_santri/index/".$this->session->userdata('id_kelas')."';
                                                   }
                                                });
                                        }
                                } else {
                                        return false;
                                }
                        }

        }
        </script>
        ";


            $data['js_grid'] = $grid_js;
            $data['content'] = $this->load->view('grid', $data, true);
            $this->load->view('main', $data);
        }
    }

    function grid_pilih_santri() {
        $valid_fields = array('Foto_Santri', 'Nama_Santri', 'Munakosah', 'Asal_Santri', 'Telepon_Santri');
        $this->flexigrid->validate_post('Foto_Santri', 'asc', $valid_fields);
        $records = $this->santri_model->get_data_santri();
        $this->output->set_header($this->config->item('json_header'));
        $no = 0;

        foreach ($records['records']->result() as $row) {
            $status_aktif = "";
            $lokasi_foto = base_url() . $row->foto_santri;
            $new_tab = 'target="_blank"';

            $record_items[] = array(
                $row->id_santri,
                $no = $no + 1,
                $row->munakosah,
				$row->nama_santri,
                $row->asal_santri,
                $row->telpon_santri
            );
        }

        if (isset($record_items))
            $this->output->set_output($this->flexigrid->json_build($records['record_count'], $record_items));
        else
            $this->output->set_output('{"page":"1","total":"0","rows":[]}');
    }
	
	//-------------------------End Pilih santri--------------------//
	
	
    function add() {
        if ($this->session->userdata('username') == NULL) {
            redirect('login');
        } else {
            $spt_ids_post_array = explode(",", $this->input->post('items'));
			$id_kelas = $this->session->userdata('id_kelas');
            foreach ($spt_ids_post_array as $index => $id) {
                if (isset($id) && $id != '') {
					$data = array(
                        'id_santri' => $id,
                        'id_kelas' => $this->session->userdata('id_kelas'),
                        'tanggal_registrasi_kelas' => date('Y-m-d')
                    );
					
					//cek data yang sama
					$sql = $this->db->query("SELECT COUNT(id_kelas_santri) AS CEK FROM kelas_santri WHERE id_santri = ".$id." AND id_kelas = ".$id_kelas."");
					$cek = '';
					
					foreach ($sql->result() as $rows) {
						$cek = $rows->CEK;
					}
					
					$msg = '';
					if ($cek > 0) {
						$msg ='Data gagal ditambahkan. Data santri sudah ada di Kelas yang dituju.';
					}
					else{
						$this->kelas_santri_model->insert($data);
						$msg ='Data santri berhasil ditambahkan.';
					}
					$this->output->set_header($this->config->item('ajax_header'));
					$this->output->set_output($msg);
                }//end if
            }//end foreach
        }
    }
    
    
    
    public function form_nilai(){
		$data['status'] = 'new';
		$data['failed'] = false;
		$data['aa'] = '';
		$data['data_form_nilai'] = $this->kelas_santri_model->data_form_nilai($this->session->userdata('id_kelas'));
		$data['content'] = $this->load->view('form_nilai', $data, true);
		$this->load->view('main', $data);
	}
	
    
	
	function save_nilai(){
		$data_form_nilai = $this->kelas_santri_model->data_form_nilai($this->session->userdata('id_kelas'));
		foreach ($data_form_nilai->result() as $row)
		{
			$data = array(
				'nilai' => $this->input->post('teori_'.$row->id_santri.''),
				'nilai_praktek' => $this->input->post('praktek_'.$row->id_santri.'')
			);
			$this->kelas_santri_model->save_nilai($row->id_santri, $row->id_kelas,$data);
		}
		redirect('kelas_santri/index/'.$this->session->userdata('id_kelas'));
	}
    

    

    function delete() {
        if ($this->session->userdata('username') == NULL) {
            redirect('login');
        } else {
            $spt_ids_post_array = explode(",", $this->input->post('items'));
  
            foreach ($spt_ids_post_array as $index => $id) {
                if (isset($id) && $id != '') {
                    $this->kelas_santri_model->delete($id);
                }//end if
            }//end foreach
        }
    }
	
	
	function generate_absensi($id_kelas){
		//$id_kelas = $this->session->userdata('id_kelas');
		$data['data_absensi'] = $this->kelas_santri_model->get_data_absensi($id_kelas);
		$data['nama_periode'] = $this->session->userdata('nama_periode');
		$data['mulai'] = $this->session->userdata('selesai');
		$data['selesai'] = $this->session->userdata('mulai');
		//$data['nama_kelas'] = $this->session->userdata('nama_kelas');
		
		//get kelas
		$hasil_kelas = $this->kelas_model->selectone($id_kelas);
		foreach ($hasil_kelas->result() as $row) {
			$data['nama_kelas'] = $row->NAMA_KELAS;
		}
		
		
		//get ustad
		$hasil = $this->kelas_santri_model->get_data_ustad($id_kelas);
		foreach ($hasil->result() as $row) {
			$data['nama_ustad'] = $row->nama_ustad;
			$data['hari'] = $row->hari;
			$data['jam'] = $row->jam;
			$data['ruang_kelas'] = $row->ruang_kelas;
			
		}
		
		
		$this->load->view('generate_absensi', $data);
	}

    function cek_validasi() {
        // Setting Rules
        $this->form_validation->set_rules('nama_santri', 'Nama Santri', 'required');
        $this->form_validation->set_rules('munakosah', 'No. Induk', 'required');

        //Setting Error Message
        $this->form_validation->set_message('required', 'Field %s harus diisi.');

        // Setting Delimiter
        $this->form_validation->set_error_delimiters('<li class="error">', '</li>');
        return $this->form_validation->run();
    }

	

}
